import {createChanel, deleteById, findOne, list, push, status, updateChannel} from '@/services/channel-api';
import {PlusOutlined} from '@ant-design/icons';
import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProFormRadio,
  ProFormText,
  ProFormTextArea,
  ProTable
} from '@ant-design/pro-components';
import {useNavigate} from 'umi';
import {Button, Drawer, message, Modal, Popover, Space} from 'antd';
import React, {useRef, useState} from 'react';
import UpdateForm from './components/UpdateForm';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.Channel) => {
  const hide = message.loading('正在添加');
  try {
    const res = await createChanel({...fields});
    hide();
    if (res) {
      message.success('添加成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.Channel) => {
  const hide = message.loading('更新中');
  try {
    const res = await updateChannel(fields);
    hide();

    if (res) {
      message.success('更细成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};


const ChannelTable: React.FC = () => {
    /**
     * @en-US Pop-up window of new window
     * @zh-CN 新建窗口的弹窗
     *  */
    const [createModalOpen, handleModalOpen] = useState<boolean>(false);
    /**
     * @en-US The pop-up window of the distribution update window
     * @zh-CN 分布更新窗口的弹窗
     * */
    const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

    const [showDetail, setShowDetail] = useState<boolean>(false);

    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<API.Channel>();
    const navigate = useNavigate();

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.Channel) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      const res = await deleteById(selectedRows.id);
      hide();
      if (res) {
        message.success('删除成功');
        actionRef.current?.reload();
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  };

    const columns: ProColumns<API.Channel>[] = [
      {
        title: 'Channel名称',
        dataIndex: 'name',
        tooltip: '查看对应pipeline',
        render: (dom, entity) => {
          return (
            <a onClick={() => {
              navigate('/admin/channel/pipeline', {state: {channelId: entity?.id}})
            }}>{dom}</a>
          );
        },
      },
      {
        title: '运行状态',
        dataIndex: 'status',
        search: true,
        hideInForm: true,
        tooltip: '',
        valueEnum: row => {
          return {
            'START': {text: '运行中', status: 'Processing'},
            'PAUSE': {
              text: (<> 挂起 {row?.canStart && row?.statusDesc !== '' &&
                <Popover content={<div style={{maxWidth: 400}}>{row?.statusDesc}</div>}/>}</>), status: 'Warning'
            },
            'STOP': {
              text: (<> 停止 {row?.canStart && row?.statusDesc !== '' &&
                <Popover content={<div style={{maxWidth: 400}}>{row?.statusDesc}</div>}/>}</>), status: 'Default'
            },
          }
        }
      },
      {
        title: '同步方向',
        dataIndex: 'pipelines',
        sorter: true,
        search: false,
        hideInForm: true,
        renderText: (pipelines: any) => {
          return pipelines?.length > 0 ? pipelines?.length > 1 ? '双向同步' : '单向同步' : '无';
        },
      },
      {
        title: '同步一致性',
        dataIndex: ['parameters', 'syncConsistency'],
        search: false,
        hideInTable: true,
        valueEnum: {
          'MEDIA': {text: '基于数据库反查'},
          'BASE': {text: '基于当前日志变更', status: 'default'}
        }
      },
      {
        title: '同步模式',
        dataIndex: ['parameters', 'syncMode'],
        search: false,
        hideInTable: true,
        valueEnum: {
          'FIELD': {text: '列记录模式', status: 'default'},
          'ROW': {text: '行记录模式', status: 'default'}
        }
      },
      {
        title: '是否开启数据一致性',
        dataIndex: ['parameters', 'enableRemedy'],
        search: false,
        hideInTable: true,
        renderText: (enableRemedy: any) => enableRemedy ? '是' : '否'
      },
      {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_, record) => (<>
          <Space>
            <a
              key="detail"
              onClick={() => {
                setCurrentRow(record);
                setShowDetail(true);
              }}
            >
              查看
            </a>

            {record.status === 'START' && (
              <>
                <a
                  type='button'
                  key="status"
                  onClick={() => {
                    Modal.confirm({
                      title: '确实关闭Channel吗?',
                      onOk: async () => {
                        try{
                          const res = await status(record.id, 'STOP');
                          if (res){
                            message.success("关闭成功");
                            actionRef?.current?.reload();
                          }
                        }catch (e){
                          // ignore
                        }

                      },
                    });
                  }}
                >停用
                </a>
              </>
            )}

            {(record?.status === 'PAUSE' || record?.status === 'STOP') && (
              <>
                {record?.canStart && (
                  <a
                    type='button'
                    key="start-channel"
                    onClick={() => {
                      Modal.confirm({
                        title: '确实开启Channel吗?',
                        onOk: async () => {
                          try{
                            const res = await status(record.id, 'START');
                            if (res){
                              message.success("开启成功");
                              actionRef?.current?.reload();
                            }
                          }catch (e){
                            // ignore
                          }

                        },
                      });
                    }}
                  >
                    {record?.status === 'STOP' ? '开启' : '解挂'}
                  </a>
                )}

                {!record?.canStart && (
                  <>
                    <a
                      key="edit"
                      onClick={() => {
                        handleUpdateModalOpen(true);
                        setCurrentRow(record);
                      }}
                    >
                      编辑
                    </a>
                    <a
                      type='button'
                      key="delete"
                      onClick={() => {
                        Modal.confirm({title: '确实删除?', onOk: () => handleRemove(record)});
                      }}
                    >删除
                    </a>
                  </>
                )}

              </>
            )}

            <a
              type='button'
              key="push"
              onClick={() => {
                Modal.confirm({
                  title: '确实推送Channel吗?',
                  onOk: () => {
                    push(record.id).then((res) => res && message.success('推送成功'));
                  },
                });
              }}
            >推送
            </a>


          </Space></>)

      }
    ];

    return (
      <PageContainer>
        <ProTable<API.RuleListItem, API.PageParams>
          headerTitle='Channel列表'
          actionRef={actionRef}
          rowKey="key"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                handleModalOpen(true);
              }}
            >
              <PlusOutlined/> 新建
            </Button>,
          ]}
          request={list}
          columns={columns}
        />
        <ModalForm
          title='新建'
          width="400px"
          open={createModalOpen}
          onOpenChange={handleModalOpen}
          onFinish={async (value) => {
            const success = await handleAdd(value as API.Channel);
            if (success) {
              handleModalOpen(false);
              await actionRef?.current?.reload();
            }
          }}
        >
          <ProFormText
            rules={[
              {
                required: true,
                message: 'channel名称不能为空',
                max: 15,
                min: 4
              },
            ]}
            width="md"
            label="Channel名称"
            name="name"
          />
          <ProFormRadio.Group
            initialValue="BASE"
            name={["parameters", "syncConsistency"]}
            label="同步一致性"
            radioType="radio"
            options={[
              {
                label: '基于数据库反查',
                value: 'MEDIA',
              },
              {
                label: '基于当前日志变更',
                value: 'BASE',
              },
            ]}/>
          <ProFormRadio.Group
            name={["parameters", "syncMode"]}
            label="同步模式"
            radioType="radio"
            initialValue="FIELD"
            options={[
              {
                label: '行记录模式',
                value: 'ROW',
              },
              {
                label: '列记录模式',
                value: 'FIELD',
              },
            ]}
          />
          <ProFormRadio.Group
            name={["parameters", "enableRemedy"]}
            label="是否开启数据一致性"
            radioType="radio"
            initialValue="false"
            options={[
              {
                label: '是 ',
                value: 'true',
              },
              {
                label: '否',
                value: 'false',
              },
            ]}/>
          <ProFormTextArea width="md" name="description" label="描述"/>
        </ModalForm>
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalOpen(false);
              setCurrentRow(undefined);
              await actionRef?.current?.reload();
            }
          }}
          onCancel={() => {
            handleUpdateModalOpen(false);
            if (!showDetail) {
              setCurrentRow(undefined);
            }
          }}
          updateModalOpen={updateModalOpen}
          values={currentRow || {}}
        />

        <Drawer
          width={500}
          open={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={false}
        >
          {currentRow?.id && (
            <ProDescriptions<API.Channel>
              column={2}
              title={currentRow?.name}
              request={async () => findOne(currentRow?.id)}
              params={{
                id: currentRow?.id,
              }}
              columns={columns as ProDescriptionsItemProps<API.Channel>[]}
            />
          )}
        </Drawer>
      </PageContainer>
    );
  }
;

export default ChannelTable;
